﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WebCycle
{
    public partial class Screensaver : Form
    {
        int _screen;
        MouseCoordinates _coords = new MouseCoordinates();

        WebCycle _parent;
        List<string> _urlCache = new List<string>();

        public Screensaver(ScreensaverThreadData ThreadData)
        {
            _screen = ThreadData.Screen;
            _parent = ThreadData.Parent;
            InitializeComponent();

            timer.Interval = _parent.Config.Delay;
            webBrowser.ScriptErrorsSuppressed = true;
        }

        private void Bail(object sender, System.EventArgs e)
        {
            _parent.Bail();
        }

        private void webBrowser_Document_MouseMove(object sender, System.EventArgs e)
        {
            HtmlElementEventArgs evtArgs = (HtmlElementEventArgs)e;

            if (_coords.X > 0 && Math.Abs(_coords.X - evtArgs.MousePosition.X) + Math.Abs(_coords.Y - evtArgs.MousePosition.Y) > 5)
            {
                Bail(sender, e);
            }
            else
            {
                _coords.X = evtArgs.MousePosition.X;
                _coords.Y = evtArgs.MousePosition.Y;
            }
        }

        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            this.webBrowser.Document.Click += Bail;
            this.webBrowser.Document.MouseMove += webBrowser_Document_MouseMove;
            if(webBrowser.Url.ToString() == "about:blank")
                NavigateNext();
            else
                timer.Start();
        }

        private void NavigateNext()
        {
            timer.Stop();
            string nextUrl = _parent.NextUrl();
            if (_urlCache.Contains(nextUrl))
            {
                _urlCache.Clear();
                //ReInitalize();
            }

            _urlCache.Add(nextUrl);

            try
            {
                
                webBrowser.Navigate(nextUrl);
            }
            catch
            {
                _parent.Bail();
            }
            // If this is the primary screen, take focus
            if (Screen.AllScreens[_screen].Primary)
            {
                this.Focus();
            }
        }

        private void ReInitalize()
        {
            this.SuspendLayout();
            webBrowser.Dispose();
            this.Controls.Remove(webBrowser);

            this.webBrowser = new System.Windows.Forms.WebBrowser();
            this.webBrowser.AllowWebBrowserDrop = false;
            this.webBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
            this.webBrowser.IsWebBrowserContextMenuEnabled = false;
            this.webBrowser.Location = new System.Drawing.Point(0, 0);
            this.webBrowser.MinimumSize = new System.Drawing.Size(20, 20);
            this.webBrowser.Name = "webBrowser";
            this.webBrowser.ScrollBarsEnabled = false;
            this.webBrowser.Size = new System.Drawing.Size(292, 269);
            this.webBrowser.TabIndex = 0;
            this.webBrowser.Url = new Uri("about:blank");
            this.webBrowser.WebBrowserShortcutsEnabled = false;
            this.webBrowser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser_DocumentCompleted);

            this.Controls.Add(webBrowser);
            this.ResumeLayout(true);
        }

        private void Screensaver_Load(object sender, EventArgs e)
        {
            Bounds = Screen.AllScreens[_screen].Bounds;
            Cursor.Hide();
            //TopMost = true;
            //NavigateNext();
            //timer.Start();
            //this.WindowState = FormWindowState.Maximized;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            NavigateNext();
        }

        private void webBrowser_KeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Right)
                NavigateNext();
            else if (e.KeyValue < 256)
                _parent.Bail();
        }   
    }

    public struct ScreensaverThreadData
    {
        public int Screen;
        public WebCycle Parent;
    }

    public struct MouseCoordinates
    {
        public int X;
        public int Y;
    }

    public class ScreensaverThread
    {
        public void Start(object data)
        {
            Application.Run(new Screensaver((ScreensaverThreadData)data));
        }
    }

}
